
#define NAV_BAR_WIDTH (20.0)
#define TAB_BAR_WIDTH (30.0)
#define NAV_TXT_WIDTH (60.0)

#define ACTIVITY_TAG 155131

#define SYSTEM_STYLE YES

#import "BaseViewController.h"

@interface BaseViewController ()<UIAlertViewDelegate>
{
    BOOL _htToasting;
    UIButton *leftView;
    UIButton *rightView;
    BOOL _ok;
    BOOL _cancel;
    void (^OKAction)(void);
    void (^CancelActon)(void);
    UIActivityIndicatorView *_activityIndicatorView;
}

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroudColor_Gray;
    // Do any additional setup after loading the view.
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    if (!SYSTEM_STYLE) {
        self.navigationItem.hidesBackButton = YES;
        [self addNavBarView:self.leftNavType location:HTNavBarLocation_Left];
        [self addNavBarView:self.rightNavType location:HTNavBarLocation_Right];
    }
}

- (void)addNavBarView:(HTNavBarType)navBarType location:(HTNavBarLocation)location
{
    if (navBarType == HTNavBarType_NoButton) {
        return;
    }
    
    UIButton *btn = nil;
    
    if (navBarType == HTNavBarType_Back) {
        UIImage *image = [UIImage imageNamed:@"back_wither"]; // back
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [btn setImage:image forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor clearColor]];
        [btn setImage:image forState:UIControlStateHighlighted];
        
    }else if (navBarType == HTNavBarType_Cart) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        [btn setBackgroundImage:[UIImage imageNamed:@"navigation_bar_cart"] forState:UIControlStateNormal];
        
    }else if (navBarType == HTNavBarType_AddFriend) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        [btn setBackgroundImage:[UIImage imageNamed:@"icon_nav_addfriend"] forState:UIControlStateNormal];
        
    }else if (navBarType == HTNavBarType_Search){
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        [btn setBackgroundImage:[UIImage imageNamed:@"search_Icon"] forState:UIControlStateNormal];
        
    }else if (navBarType == HTNavBarType_More) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        [btn setBackgroundImage:[UIImage imageNamed:@"navigation_bar_more"] forState:UIControlStateNormal];
        
    }else if (navBarType == HTNavBarType_Camera) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        [btn setBackgroundImage:[UIImage imageNamed:@"icon_nav_camera"] forState:UIControlStateNormal];
        
    }else if (navBarType == HTNavBarType_Share) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_BAR_WIDTH, NAV_BAR_WIDTH)];
        [btn setBackgroundImage:[UIImage imageNamed:@"icon_nav_share"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"icon_nav_share_press"] forState:UIControlStateFocused];
        
    }else if (navBarType == HTNavBarType_Text) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, NAV_TXT_WIDTH, NAV_BAR_WIDTH)];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if ([self.rightButtonText isEqualToString:@"+"]) {
            [btn.titleLabel setFont:FONT(25)];
        }else
        {
            [btn.titleLabel setFont:FONT(15)];
        }
        if (location == HTNavBarLocation_Left) {
            
        }else if (location == HTNavBarLocation_Right ) {
            [btn setTitle:self.rightButtonText forState:UIControlStateNormal];
            btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        }
    }
    
    if (btn == nil) {
        return;
    }
    
    if (location == HTNavBarLocation_Left) {
        leftView = btn;
        if (self.leftNaviBarButtonSelector) {
            [leftView addTarget:self action:self.leftNaviBarButtonSelector forControlEvents:UIControlEventTouchUpInside];
        }else{
            [leftView addTarget:self action:@selector(tapLeftView) forControlEvents:UIControlEventTouchUpInside];
        }
        UIBarButtonItem *negativeSpacer = [[ UIBarButtonItem alloc ] initWithBarButtonSystemItem : UIBarButtonSystemItemFixedSpace
                                                                                          target : nil action : nil ];
        negativeSpacer. width = - 10 ;
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftItem];
        
    }else if (location == HTNavBarLocation_Right) {
        rightView = btn;
        
        if (self.disableRightButton) {
            [rightView setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        }
        
        if (self.rightNaviBarButtonSelector) {
            [rightView addTarget:self action:self.rightNaviBarButtonSelector forControlEvents:UIControlEventTouchUpInside];
        }else{
            [rightView addTarget:self action:@selector(tapRightView) forControlEvents:UIControlEventTouchUpInside];
        }
        
        UIBarButtonItem *negativeSpacer = [[ UIBarButtonItem alloc ] initWithBarButtonSystemItem : UIBarButtonSystemItemFixedSpace
                                                                                          target : nil action : nil ];
        negativeSpacer. width = -5 ;
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,rightItem];
        
    }
}

- (void)hideRightView
{
    rightView.hidden = YES;
}
- (void)showRihghtView
{
    rightView.hidden = NO;
}

- (void)dealloc
{
    removeNObserver();
    
    leftView = nil;
    rightView = nil;
    
}

- (void)tapLeftView
{
    if (self.leftNavType == HTNavBarType_Back) {
        if ([[self.navigationController viewControllers] count] == 1) {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)tapRightView
{
    if (_disableRightButton) {
        return;
    }
}

- (void)toastTitle:(NSString*)title message:(NSString*)message {
    [self showHtToastWithTitle:title message:message positon:CSToastPositionCenter action:nil];
}

- (void)toastTitle:(NSString*)title message:(NSString*)message action:(void(^)())block {
    [self showHtToastWithTitle:title message:message positon:CSToastPositionCenter action:block];
}

- (void)showHtToastWithTitle:(NSString *)title message:(NSString *)message custompositonForTop:(CGFloat)positionY action:(void(^)())block
{
    [self showHtToastWithTitle:title message:message positon:[NSNumber numberWithFloat:positionY] action:block];
}


- (void)showHtToastWithTitle:(NSString *)title message:(NSString *)message positon:(id)position action:(void(^)())block
{
    if (_htToasting) {
        return;
    }
    
    _htToasting = YES;
    
    CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle];
    style.titleAlignment = NSTextAlignmentRight;
    style.titleColor =RGB(64, 145, 32);
    style.titleFont = FONT(16);
    style.titleNumberOfLines = 0;
    style.messageFont = FONT(14);
    style.messageNumberOfLines = 0;
    style.messageAlignment = NSTextAlignmentCenter;
    style.messageColor = [UIColor whiteColor];
    style.cornerRadius = 3.0;
    id currentPostion;
    if (position) {
        if ([position isKindOfClass:[NSNumber class]]) {
            
            UIView *toast = [self.view toastViewForMessage:message title:title image:nil style:style];
            [self.view showToast:toast duration:2.0 position:[NSValue valueWithCGPoint:CGPointMake(SCREEN_WIGHT/2.0, [position floatValue])] completion:^(BOOL didTap) {
                _htToasting = NO;
            }];
            return;
        }else
        {
            
            currentPostion = position;
        }
    }else
    {
        currentPostion = CSToastPositionCenter;
    }
    if (NULL_OR_EMPTY(title)) {
        [self.view makeToast:message duration:1.0 position:currentPostion title:nil image:nil style:style completion:^(BOOL didTap) {
            _htToasting = NO;
            if (block) {
                block();
            }
        }];
        //[self.view makeToast:message duration:2.0 position:currentPostion style:style];
        
    }else
    {
        [self.view makeToast:message duration:1.0 position:currentPostion title:title image:nil style:style completion:^(BOOL didTap) {
            _htToasting = NO;
            if (block) {
                block();
            }
        }];
    }
    
}

- (void)alertTitle:(NSString *)title message:(NSString *)message {
    if (MF_Version_Greater_Or_Equal(8.0)) {
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:title
                                                                    message:message
                                                             preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction *action) {
                                                             
                                                         }];
        [ac addAction:okAction];
        [self presentViewController:ac animated:YES completion:^{
            
        }];
    }else {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:title
                                                     message:message
                                                    delegate:nil
                                           cancelButtonTitle:nil
                                           otherButtonTitles:@"确定", nil];
        [av show];
    }
}

- (void)alertTitle:(NSString*)title message:(NSString*)message ok:(BOOL)ok okAction:(void(^)(void))okAction cancel:(BOOL)cancel cancelAction:(void(^)(void))cancelAction {
    if (MF_Version_Greater_Or_Equal(8.0)) {
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:title
                                                                    message:message
                                                             preferredStyle:UIAlertControllerStyleAlert];
        if (ok) {
            UIAlertAction *okAct = [UIAlertAction actionWithTitle:@"确定"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction *action) {
                                                              okAction();
                                                          }];
            [ac addAction:okAct];
        }
        
        if (cancel) {
            UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"取消"
                                                                style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction *action) {
                                                                  cancelAction();
                                                              }];
            [ac addAction:cancelAct];
        }
        
        [self presentViewController:ac animated:YES completion:^{
            
        }];
    }else {
        UIAlertView *av = nil;
        if (ok && cancel) {
            av = [[UIAlertView alloc] initWithTitle:title
                                            message:message
                                           delegate:self
                                  cancelButtonTitle:@"取消"
                                  otherButtonTitles:@"确定", nil];
            _ok = YES;
            _cancel = YES;
            OKAction = okAction;
            CancelActon = cancelAction;
        }else if (ok) {
            av = [[UIAlertView alloc] initWithTitle:title
                                            message:message
                                           delegate:self
                                  cancelButtonTitle:nil
                                  otherButtonTitles:@"确定", nil];
            _ok = YES;
            _cancel = NO;
            OKAction = okAction;
            CancelActon = nil;
            
        }else if (cancel) {
            av = [[UIAlertView alloc] initWithTitle:title
                                            message:message
                                           delegate:self
                                  cancelButtonTitle:@"取消"
                                  otherButtonTitles:nil];
            _ok = NO;
            _cancel = YES;
            OKAction = nil;
            CancelActon = cancelAction;
            
        }else {
            av = [[UIAlertView alloc] initWithTitle:title
                                            message:message
                                           delegate:nil
                                  cancelButtonTitle:@"取消"
                                  otherButtonTitles:nil];
            _ok = NO;
            _cancel = NO;
            OKAction = nil;
            CancelActon = nil;
        }
        [av show];
    }
}

#pragma mark - delegate alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (_ok && _cancel) {
        if (buttonIndex == 0) {
            // Cancel
            CancelActon();
            
        }else if (buttonIndex == 1) {
            // OK
            OKAction();
            
        }
    }else if (_ok) {
        if (buttonIndex == 0) {
            // OK
            OKAction();
            
        }
        
    }else if (_cancel) {
        if (buttonIndex == 0) {
            // Cancel
            CancelActon();
            
        }
    }else {
        // Miss
    }
}

- (void)canceFirstResponder
{
    [[self findFirstResponderBeneathView:self.view] resignFirstResponder];
}

- (UIView*)findFirstResponderBeneathView:(UIView*)view

{
    for ( UIView *childView in view.subviews ) {
        
        if ([childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder] )
        {
            return childView;
        }
        
        UIView *result = [self findFirstResponderBeneathView:childView];
        
        if ( result )
            
            return result;
    }
    
    return nil;
    
}

#pragma mark - 加载/取消加载方法
-(void)startLoadingAnimation {
    //    [self.view makeToastActivity:CSToastPositionCenter];
    [self startLoadingAnimationTraditional];
}

-(void)stopLoadingAnimation {
    //    [self.view hideToastActivity];
    [self stopLoadingAnimationTraditional];
}

-(void)startLoadingAnimationTraditional {
    if (_activityIndicatorView == nil) {
        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _activityIndicatorView.frame = CGRectMake(0, 0, 50, 50);
        [_activityIndicatorView setCenter:CGPointMake(SCREEN_WIGHT/2, SCREEN_HEIGHT/2-50)];
        [self.view addSubview:_activityIndicatorView];
    }
    _activityIndicatorView.hidden = NO;
    [_activityIndicatorView startAnimating];
}

-(void)stopLoadingAnimationTraditional {
    if (_activityIndicatorView) {
        [_activityIndicatorView stopAnimating];
        _activityIndicatorView.hidden = YES;
    }
}


- (void)startLoadingAnimationInView:(UIView*)view
{
    for (id v in [view subviews]) {
        if ([v isKindOfClass:[UIActivityIndicatorView class]]) {
            UIActivityIndicatorView *indicatorView = v;
            if (indicatorView.tag == ACTIVITY_TAG) {
                [indicatorView startAnimating];
                return;
            }
        }
    }
    
    UIActivityIndicatorView *_activityIndicatorSmallView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicatorSmallView.tag = ACTIVITY_TAG;
    _activityIndicatorSmallView.frame = CGRectMake(0, 0, 30, 30);
    [_activityIndicatorSmallView setCenter:CGPointMake(view.frame.size.width/2, view.frame.size.height/2)];
    [view addSubview:_activityIndicatorSmallView];
    _activityIndicatorSmallView.hidden = NO;
    [_activityIndicatorSmallView startAnimating];
}

- (void)stopLoadingAnimationInView:(UIView*)view
{
    for (id v in [view subviews]) {
        if ([v isKindOfClass:[UIActivityIndicatorView class]]) {
            UIActivityIndicatorView *indicatorView = v;
            if (indicatorView.tag == ACTIVITY_TAG) {
                [indicatorView stopAnimating];
                [indicatorView removeFromSuperview];
                break;
            }
        }
    }
}

@end
